package com.danskin.wechat.web;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.third.JwThirdAPI;
import org.jeewx.api.third.model.ApiComponentToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.danskin.wechat.api.client.WeiXinOpenApiClient;
import com.danskin.wechat.config.DanskinConfig;
import com.danskin.wechat.entity.WxAuthTicket;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.model.LoginUser;
import com.danskin.wechat.service.UserService;
import com.danskin.wechat.service.WechatOpService;
import com.danskin.wechat.util.DateTools;
import com.danskin.wechat.util.Page;

public class BaseController {

	public final static Logger logger = Logger.getLogger(BaseController.class);

	/**
	 * 微信全网账号
	 */

	@Value("${component_appid}")
	protected String COMPONENT_APPID;
	@Value("${component_appsecret}")
	protected String COMPONENT_APPSECRET;
	// protected final static String COMPONENT_APPID = "wx6088cabc0a099afc";
	// protected final static String COMPONENT_APPSECRET =
	// "fb6478bb1022aa27a47b92619632b5e9";

	@Autowired
	public DanskinConfig config;
	@Autowired
	public WechatOpService wechatOpService;

	@Autowired
	public UserService userService;

	protected Map<String, String> VipLevel = new HashMap<String, String>();

	public BaseController() {
		VipLevel.put("v0", "非会员");
		VipLevel.put("v1", "新锐会员");
		VipLevel.put("v2", "菁英会员");
		VipLevel.put("v3", "铜牌会员");
		VipLevel.put("v4", "银牌会员");
		VipLevel.put("v5", "金牌会员");
		VipLevel.put("v6", "韦德会员");
	}

	/**
	 * 获取第三方平台ACCESS_TOKEN
	 * 
	 * @author Allen Liu
	 * @return String
	 * @throws WexinReqException
	 */
	protected String getComponentAccessToken() throws WexinReqException {

		WxAuthTicket entity = wechatOpService.getAuthTicket(COMPONENT_APPID);
		if (entity != null) {
			Date now = new Date();
			if (entity.getAccessToken() == null || now.getTime() > entity.getAccessTokenExpires().getTime()) { // 过期将重取
				ApiComponentToken apiComponentToken = new ApiComponentToken();
				apiComponentToken.setComponent_appid(COMPONENT_APPID);
				apiComponentToken.setComponent_appsecret(COMPONENT_APPSECRET);
				apiComponentToken.setComponent_verify_ticket(entity.getTicket());

				String component_access_token = JwThirdAPI.getAccessToken(apiComponentToken);
				// 更新access_token
				entity.setAccessToken(component_access_token);
				entity.setAccessTokenExpires(DateTools.getDateTools().operationHour(now, 2, true));
				wechatOpService.saveOrUpdateTicket(entity);

				return component_access_token;
			}

			return entity.getAccessToken();
		}

		return "";
	}

	/**
	 * 获取公众号ACCESS_TOKEN
	 * 
	 * @author Allen Liu
	 * @return String
	 * @throws WexinReqException
	 */
	protected String getMPAccessToken() {

		return this.getMPWithAccessToken(this.getMpId());
	}

	protected String getMPWithAccessToken(int mpId) {

		WxMediaPlatform entity = wechatOpService.queryMediaPlatform(mpId);
		if (entity != null) {
			Date now = new Date();
			if (entity.getAccessToken() == null || now.getTime() > entity.getAccessTokenExpires().getTime()) { // 过期将重取

				String component_access_token;
				try {
					component_access_token = this.getComponentAccessToken();

					JSONObject json = WeiXinOpenApiClient.createInstance().getAuthorizerToken(component_access_token,
							COMPONENT_APPID, entity.getAppId(), entity.getRefreshToken());

					if (json != null) {
						String authorizer_access_token = json.getString("authorizer_access_token");
						// 更新access_token
						entity.setAccessToken(authorizer_access_token);
						entity.setRefreshToken(json.getString("authorizer_refresh_token"));
						entity.setAccessTokenExpires(
								DateTools.getDateTools().operationSecond(now, json.getInteger("expires_in")));
						// 更新至数据库
						wechatOpService.saveWxMediaPlatform(entity);

						return authorizer_access_token;
					}
					return "";

				} catch (WexinReqException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return "";
			}

			return entity.getAccessToken();
		}

		return "";
	}

	public Object pagelistToJSONForBootStrapTable(List<?> pdList, Page page) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (null != pdList) {
			if (null != page) {
				map.put("total", page.getTotalResult());
			}
			map.put("rows", pdList);
		} else {
			map.put("rows", null);
		}
		return map;
	}

	/**
	 * 获取当前登录用户信息
	 * 
	 * @return
	 */
	protected LoginUser getLoginUser() {
		/*
		 * String token=CookieUtils.getCookieValue(this.getRequest(),
		 * "SESSION_TOKEN"); UserInfo user=userService.getUserByToken(token);
		 * LoginUser loginUser=new LoginUser();
		 * loginUser.setUserId(user.getId());
		 * loginUser.setUserName(user.getUserName());
		 * loginUser.setMpId(user.getMpId());
		 * loginUser.setIp(this.getRequest().getRemoteHost());
		 */
		LoginUser attribute = (LoginUser) this.getRequest().getAttribute("loginUser");
		return attribute;
	}

	/**
	 * 获取当前登录用户ID
	 * 
	 * @return
	 */
	protected int getUserId() {
		return this.getLoginUser().getUserId();
	}

	/**
	 * 获取公众平台ID
	 * 
	 * @return
	 */
	protected int getMpId() {
		return this.getLoginUser().getMpId();
	}

	/**
	 * 得到request对象
	 * 
	 * @return
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request;
	}

	/**
	 * 得到ModelAndView
	 * 
	 * @return
	 */
	public ModelAndView getModelAndView() {
		return new ModelAndView();
	}

	@SuppressWarnings("rawtypes")
	public Map getRequestParameter(HttpServletRequest request) throws UnsupportedEncodingException {
		Map properties = request.getParameterMap();
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {
				value = "";
			} else if (valueObj instanceof String[]) {

				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
			} else {
				value = valueObj.toString();
			}
			value = new String(value.getBytes("iso-8859-1"), "UTF-8");
			returnMap.put(name, value);
		}
		return returnMap;
	}
	


	protected String getMapValue(String key, Map<String, Object> map) {
		if (map.containsKey(key)) {
			Object obj = map.get(key);
			if (obj != null) {
				return map.get(key).toString();
			}
		}
		return null;
	}

}
